// 创建预览弹窗
function createPreviewModal() {
    const modal = document.createElement('div');
    modal.id = 'json-preview-modal';
    modal.innerHTML = `
    <div class="json-preview-overlay">
      <div class="json-preview-container">
        <div class="json-preview-header">
          <h3>JSON格式化预览</h3>
          <div class="header-controls">
            <span class="data-status" id="data-status">完整JSON</span>
            <button class="copy-btn" title="复制内容">📋</button>
            <button class="close-btn">&times;</button>
          </div>
        </div>
        <div class="json-preview-content">
          <div class="content-tabs">
            <button class="tab-btn active" data-tab="smart">智能格式化</button>
            <button class="tab-btn" data-tab="partial">不完整JSON预览</button>
            <button class="tab-btn" data-tab="raw">原始数据</button>
          </div>
          <div class="tab-content">
            <div id="smart-content" class="tab-pane active"></div>
            <div id="partial-content" class="tab-pane"></div>
            <div id="raw-content" class="tab-pane">
              <pre id="json-display"></pre>
            </div>
          </div>
        </div>
      </div>
    </div>
  `;

    document.body.appendChild(modal);

    // 添加事件监听
    setupModalEvents(modal);
    return modal;
}

// 设置弹窗事件
function setupModalEvents(modal) {
    const closeBtn = modal.querySelector('.close-btn');
    const overlay = modal.querySelector('.json-preview-overlay');
    const copyBtn = modal.querySelector('.copy-btn');
    const tabBtns = modal.querySelectorAll('.tab-btn');

    closeBtn.addEventListener('click', closePreview);
    overlay.addEventListener('click', (e) => {
        if (e.target === overlay) closePreview();
    });

    copyBtn.addEventListener('click', copyFormattedContent);

    // 标签页切换
    tabBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            const tabName = e.target.dataset.tab;
            switchTab(tabName);
        });
    });

    // ESC键关闭
    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') closePreview();
    });
}

// 切换标签页
function switchTab(tabName) {
    // 更新按钮状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.toggle('active', btn.dataset.tab === tabName);
    });

    // 更新内容显示
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.toggle('active', pane.id === `${tabName}-content`);
    });
}

// 复制内容
function copyFormattedContent() {
    const activePane = document.querySelector('.tab-pane.active');
    const textToCopy = activePane.textContent || activePane.innerText;

    navigator.clipboard.writeText(textToCopy).then(() => {
        const copyBtn = document.querySelector('.copy-btn');
        const originalText = copyBtn.textContent;
        copyBtn.textContent = '✅';
        setTimeout(() => {
            copyBtn.textContent = originalText;
        }, 2000);
    });
}

// 关闭预览
function closePreview() {
    const modal = document.getElementById('json-preview-modal');
    if (modal) modal.remove();
}

// 增强的富文本处理函数
function processRichText(content) {
    if (typeof content !== 'string') return content;

    // 处理常见的转义序列
    let processed = content
        // 处理换行符
        .replace(/\\n/g, '\n')
        // 处理制表符
        .replace(/\\t/g, '\t')
        // 处理回车符
        .replace(/\\r/g, '\r')
        // 处理双引号
        .replace(/\\"/g, '"')
        // 处理单引号
        .replace(/\\'/g, "'")
        // 处理反斜杠
        .replace(/\\\\/g, '\\')
        // 处理Unicode转义序列
        .replace(/\\u([0-9a-fA-F]{4})/g, (match, grp) => String.fromCharCode(parseInt(grp, 16)))
        // 处理十六进制转义
        .replace(/\\x([0-9a-fA-F]{2})/g, (match, grp) => String.fromCharCode(parseInt(grp, 16)));

    return processed;
}

// 智能JSON结构分析
function analyzeJsonStructure(text) {
    let result = {
        success: false,
        type: 'unknown',
        data: null,
        formatted: '',
        message: ''
    };

    // 首先尝试完整解析
    try {
        const parsed = JSON.parse(text);
        result.success = true;
        result.type = 'complete';
        result.data = parsed;
        result.message = '完整JSON格式';
        return result;
    } catch (e) {
        // 如果不是完整JSON，分析结构并尝试格式化显示
        return formatPartialJson(text);
    }
}

// 格式化不完整的JSON，同时处理转义字符
function formatPartialJson(text) {
    let formatted = '';
    let indentLevel = 0;
    let inString = false;
    let escapeNext = false;
    let currentString = '';
    let stack = [];

    // 分析文本结构
    for (let i = 0; i < text.length; i++) {
        const char = text[i];

        if (escapeNext) {
            currentString += char;
            escapeNext = false;
            continue;
        }

        if (char === '\\') {
            if (inString) {
                currentString += char;
                escapeNext = true;
            } else {
                formatted += char;
            }
            continue;
        }

        if (char === '"' && !escapeNext) {
            if (inString) {
                // 字符串结束
                currentString += char;
                // 处理字符串中的转义字符
                const processedString = processRichText(currentString);
                formatted += processedString;
                currentString = '';
                inString = false;
            } else {
                // 字符串开始
                inString = true;
                currentString = char;
            }
            continue;
        }

        if (inString) {
            currentString += char;
            continue;
        }

        // 不在字符串中，处理JSON结构
        switch (char) {
            case '{':
            case '[':
                formatted += char + '\n' + '  '.repeat(++indentLevel);
                stack.push(char === '{' ? '}' : ']');
                break;

            case '}':
            case ']':
                if (stack.length > 0 && stack[stack.length - 1] === char) {
                    stack.pop();
                    formatted += '\n' + '  '.repeat(--indentLevel) + char;
                } else {
                    formatted += char;
                }
                break;

            case ',':
                formatted += ',\n' + '  '.repeat(indentLevel);
                break;

            case ':':
                formatted += ': ';
                break;

            default:
                formatted += char;
        }
    }

    // 如果文本结束但字符串还未结束，添加剩余字符串内容
    if (inString && currentString) {
        const processedString = processRichText(currentString);
        formatted += processedString;
    }

    const isComplete = stack.length === 0;

    return {
        success: !isComplete, // 如果不完整，也算"成功"，因为我们还是要显示
        type: isComplete ? 'complete' : 'partial',
        data: text,
        formatted: formatted,
        message: isComplete ? '完整JSON格式' : `不完整JSON (缺少 ${stack.length} 个结束符号)`
    };
}

// 创建智能格式化显示
function createSmartDisplay(content) {
    const container = document.createElement('div');
    container.className = 'json-formatted-display';

    const analysis = analyzeJsonStructure(content);

    // 更新状态显示
    const statusElement = document.getElementById('data-status');
    if (statusElement) {
        statusElement.textContent = analysis.message;
        statusElement.className = `data-status ${analysis.type}`;
    }

    // 创建代码显示区域
    const codeElement = document.createElement('pre');
    codeElement.className = 'json-code';

    if (analysis.type === 'complete' && analysis.success) {
        // 完整JSON的格式化显示 - 使用自定义格式化函数处理转义字符
        const formattedJson = formatJsonWithEscapes(analysis.data);
        codeElement.innerHTML = highlightJson(formattedJson);
    } else {
        // 不完整JSON的格式化显示 - 已经处理了转义字符
        codeElement.innerHTML = highlightJson(analysis.formatted);
    }

    container.appendChild(codeElement);
    return container;
}

// 自定义JSON格式化函数，处理转义字符
function formatJsonWithEscapes(obj, indent = 2) {
    const processValue = (value, currentIndent) => {
        if (typeof value === 'string') {
            // 处理字符串中的转义字符
            const processed = processRichText(value);
            // 如果字符串包含换行，特殊处理
            if (processed.includes('\n')) {
                const lines = processed.split('\n');
                if (lines.length > 1) {
                    // 多行字符串，每行单独处理
                    return '"' + lines[0] +
                        lines.slice(1).map(line => '\n' + ' '.repeat(currentIndent + 6) + line).join('') + '"';
                }
            }
            return '"' + processed + '"';
        } else if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
            return String(value);
        } else if (Array.isArray(value)) {
            if (value.length === 0) return '[]';

            const items = value.map(item =>
                ' '.repeat(currentIndent + indent) + processValue(item, currentIndent + indent)
            ).join(',\n');

            return '[\n' + items + '\n' + ' '.repeat(currentIndent) + ']';
        } else if (typeof value === 'object') {
            const keys = Object.keys(value);
            if (keys.length === 0) return '{}';

            const items = keys.map(key => {
                const formattedKey = '"' + key + '": ';
                const formattedValue = processValue(value[key], currentIndent + indent);
                return ' '.repeat(currentIndent + indent) + formattedKey + formattedValue;
            }).join(',\n');

            return '{\n' + items + '\n' + ' '.repeat(currentIndent) + '}';
        }

        return '""';
    };

    return processValue(obj, 0);
}

// 创建不完整JSON格式化显示
function createPartialDisplay(content) {
    const container = document.createElement('div');
    container.className = 'json-formatted-display';

    // 强制使用不完整JSON格式化
    const partialResult = formatPartialJson(content);

    // 创建代码显示区域
    const codeElement = document.createElement('pre');
    codeElement.className = 'json-code';
    codeElement.innerHTML = highlightJson(partialResult.formatted);

    // 添加状态指示
    const statusDiv = document.createElement('div');
    statusDiv.className = `partial-status ${partialResult.type}`;
    statusDiv.textContent = `强制不完整JSON显示: ${partialResult.message}`;
    container.appendChild(statusDiv);
    container.appendChild(codeElement);

    return container;
}

// 创建原始数据显示
function createRawDisplay(content) {
    const container = document.createElement('div');
    container.className = 'json-formatted-display';

    // 创建代码显示区域
    const codeElement = document.createElement('pre');
    codeElement.className = 'json-code';

    // 原始数据显示，只做HTML转义，不做其他处理
    codeElement.textContent = content;

    container.appendChild(codeElement);
    return container;
}

// HTML转义函数
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}

// 监听来自background的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === "showJsonPreview") {
        // 移除已存在的弹窗
        const existingModal = document.getElementById('json-preview-modal');
        if (existingModal) existingModal.remove();

        // 创建新弹窗
        const modal = createPreviewModal();

        // 设置三个选项卡的内容
        const smartContent = modal.querySelector('#smart-content');
        const partialContent = modal.querySelector('#partial-content');
        const rawContent = modal.querySelector('#raw-content');

        // 智能格式化显示
        const smartDisplay = createSmartDisplay(request.selectedText);
        smartContent.appendChild(smartDisplay);

        // 不完整JSON显示
        const partialDisplay = createPartialDisplay(request.selectedText);
        partialContent.appendChild(partialDisplay);

        // 原始数据显示
        const rawDisplay = createRawDisplay(request.selectedText);
        rawContent.appendChild(rawDisplay);

        // 显示弹窗
        setTimeout(() => {
            modal.style.display = 'block';
        }, 100);
    }
});

// 语法高亮函数
function highlightJson(formattedJson) {
    return escapeHtml(formattedJson)
        .replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*")(\s*:)?/g, (match, stringPart, _, colonPart) => {
            if (colonPart) {
                return `<span class="json-key">${stringPart}</span><span class="json-colon">${colonPart}</span>`;
            }
            return `<span class="json-string">${stringPart}</span>`;
        })
        .replace(/\b(true|false|null)\b/g, '<span class="json-boolean">$&</span>')
        .replace(/\b-?\d+(\.\d+)?([eE][+-]?\d+)?\b/g, '<span class="json-number">$&</span>')
        .replace(/(\{|\[)/g, '<span class="json-bracket">$&</span>')
        .replace(/(\}|\])/g, '<span class="json-bracket">$&</span>');
}